#pragma once
#include <iostream>
#include <unordered_map>
#include <vector>
#include <string>
#include <fstream>
#include <algorithm>
#include "log.hpp"
const std::string unknown = "unknown";
const std::string mydict = "./recource/dict.txt";
const char sep = ' ';
namespace Trans
{
    class Word
    {
        // 单词， 音标， 中文解释， 类型， 相近
    };

    class Translate
    {
    public:
        Translate(std::string dict_path = mydict) : _dict_path(dict_path)
        {
            LoadDict();
            Parse();
        }

        void LoadDict()
        {
            std::ifstream in(_dict_path);
            std::string line;
            while (std::getline(in, line))
            {
                lines.push_back(line);
            }

            in.close();
            lg.LogMessage(Debug, "Load dict txt sucess, path: %s", _dict_path.c_str());
        }

        void Parse()
        {
            for (auto &line : lines)
            {
                std::reverse(line.begin(), line.end());
                std::string re = line;
                std::reverse(line.begin(), line.end());
                int cnt = 0;
                // std::cout << re << std::endl;
                for (int i = 0; i < re.size(); i++)
                {
                    if (re[i] != sep)
                        cnt++;
                    else
                        break;
                }

                if (cnt == re.size())
                    continue;
                else
                {
                    std::string chinese = re.substr(0, cnt + 1);
                    // std::cout << '#' << chinese << std::endl;
                    std::reverse(chinese.begin(), chinese.end());
                    std::string word = line.substr(0, line.size() - chinese.size());
                    // std::cout  << chinese << ' ' << word << std::endl;
                    _dict.insert(std::make_pair(word, chinese));
                }
            }
            lg.LogMessage(Debug, "Parse dict txt sucess, path: %s", _dict_path.c_str());
        }

        void debug()
        {
            // for(auto &line:lines) std::cout << line << std::endl;

            for (auto elem : _dict)
            {
                std::cout << elem.first << " : " << elem.second << std::endl;
            }
        }

        std::string Excute(const std::string &word)
        {
            auto iter = _dict.find(word);
            if (iter == _dict.end())
                return "unknown";
            else
                return _dict[word];
        }

        ~Translate()
        {
        }

    private:
        std::string _dict_path;
        std::unordered_map<std::string, std::string> _dict;
        std::vector<std::string> lines;
    };
}
